/* eslint-disable jsx-a11y/anchor-is-valid */
/*
 * @Author: Zhouhai 497675647@qq.com
 * @Date: 2022-10-26 17:05:31
 * @LastEditors: Zhouhai 497675647@qq.com
 * @LastEditTime: 2024-05-29 15:06:30
 */
/* eslint-disable @typescript-eslint/no-unused-vars */
import React, { useEffect, useRef, useState } from 'react'
import { Button, message, Popconfirm, Space } from 'antd';
import PageDiv from '@/components/PageDiv';
import { DictDataDomain } from '@/type.d/system';
import { GenTableDomain } from '@/type.d/tool';
import { ActionType, ProColumns, ProFormColumnsType, ProFormDateRangePicker, ProFormInstance, ProFormText, QueryFilter } from '@ant-design/pro-components';
import ResizeTable from '@/components/ResizeTable';
import { getDictDatasByDictTypes } from '@/api/system/dictData';
import { useStore } from '@/store';
import {
    listTable,
    delTable,
    updateGenTable,
    previewTable,
    getGenTable,
    synchDb,
    genCode
} from '@/api/tool/gen';
import { pageInfo } from '@/type.d/ajaxResult';
import './index.less';
import ImportTable from './importTable';
import Viewcode from './viewcode';
import GenEdit from './edit/edit';
import download from '@/plugins/download';


const Gen: React.FC = () => {
    const { layoutStore, userStore } = useStore();

    const actionRef = useRef<ActionType>();
    const formRef = useRef<ProFormInstance<GenTableDomain>>();
    const queryformRef = useRef<ProFormInstance<GenTableDomain>>();
    const [queryValue, setQueryValue] = useState<GenTableDomain>({});
    const [statusOptions, setStatusOptions] = useState<any[]>([]);
    const [tableListDataSource, setTableListDataSource] = useState<GenTableDomain[]>([]);

    const [pageStatus, setPageStatus] = useState<'List' | 'Card'>('List');

    const [cardData, setCardData] = useState<GenTableDomain>({});

    const [importModal, setImportModal] = useState<boolean>(false);

    const [codeViewData, setCodeViewData] = useState<Record<string, string>>({})
    const [codeViewVisible, setCodeViewVisible] = useState<boolean>(false)


    const [pageInfo, setPageInfo] = useState<pageInfo>({
        current: 1,
        pageSize: 10,
        total: 0
    });

    const newdata = {
        corpCode: '',
        corpName: '',
        taxpayerid: '',
        pkFathercorp: '',
        enablestate: '0',
        remark: '',
    }

    /**
 * 表单字段配置
 */
    const formConfig: ProFormColumnsType<GenTableDomain>[] = [
        {
            title: '上级公司',
            key: 'pkFathercorp',
            valueType: 'text',
            dataIndex: 'string',
            colProps: { md: 8, xl: 6 },
            fieldProps: {
                disabled: 'true'
            }
        },
        {
            title: '公司名称',
            key: 'corpName',
            valueType: 'text',
            dataIndex: 'string',
            colProps: { md: 8, xl: 6 }
        },
        {
            title: '公司编码',
            key: 'corpCode',
            valueType: 'text',
            colProps: { md: 8, xl: 6 }
        },
        {
            title: '企业信用代码',
            key: 'taxpayerid',
            valueType: 'text',
            colProps: { md: 8, xl: 6 },
        },
        {
            title: '负责人',
            key: 'leader',
            valueType: 'text',
            colProps: { md: 8, xl: 6 },
        },
        {
            title: '联系电话',
            key: 'phone',
            valueType: 'text',
            colProps: { md: 8, xl: 6 },
        },
        {
            title: '联系地址',
            key: 'address',
            valueType: 'text',
            colProps: { md: 8, xl: 6 },
        },
        {
            title: '启用状态',
            key: 'enablestate',
            valueType: 'radio',
            colProps: { md: 8, xl: 6 },
            fieldProps: {
                disabled: true,
                options: statusOptions
            }
        },
        {
            title: '备注',
            key: 'remark',
            valueType: 'textarea',
            colProps: { md: 24, xl: 24 },
        },
    ];


    const columns: ProColumns<GenTableDomain>[] = [
        {
            title: '表名称',
            dataIndex: 'tableName',
            fixed: 'left'
        },
        {
            title: '表描述',
            dataIndex: 'tableComment',
            fixed: 'left'
        },
        {
            title: '实体',
            dataIndex: 'className',
            fixed: 'left'
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            fixed: 'left'
        },
        {
            title: '更新时间',
            dataIndex: 'updateTime',
            fixed: 'left',
            valueType: 'text',
        },
        {
            title: '操作',
            width: 180,
            key: 'option',
            valueType: 'option',
            render: (_dom: React.ReactNode, entity: GenTableDomain) => [
                <a key="view" hidden={!userStore.hasPerms('system:gen:preview')} onClick={() => {
                    onView(entity)
                }}>预览</a>,
                <a key="edit" hidden={!userStore.hasPerms('system:gen:edit')} onClick={() => {
                    onEdit(entity)
                }}>编辑</a>,
                <a hidden={!userStore.hasPerms('system:gen:remove')}>
                    <Popconfirm key="confirmdelete" title="确定要删除数据吗？" okText="是" cancelText="否" onConfirm={() => {
                        onDelete(entity)
                    }}>
                        <a key="delete" >删除</a>
                    </Popconfirm>
                </a>,
                <a hidden={!userStore.hasPerms('system:gen:sync')}>
                    <Popconfirm key="confirmsync" title={`是否确认要强制同步${entity.tableName}表结构吗？`} okText="是" cancelText="否" onConfirm={() => {
                        onSyncDB(entity)
                    }}>
                        <a key="sync" >同步</a>
                    </Popconfirm>
                </a>,
                <a key="gen" hidden={!userStore.hasPerms('system:gen:code')} onClick={() => {
                    onGenCode(entity)
                }}>生成代码</a>,


            ],
        },
    ];

    const onGenCode = (data: GenTableDomain) => {
        if (data.tableName) {
            if (data.genType === "1") {
                genCode(data.tableName).then((res) => {
                    if (res.code === 200) {
                        message.success("成功生成到自定义路径：" + data.genPath);
                    } else {
                        message.error('生成失败：' + res?.msg);
                    }
                }).finally(() => {
                    layoutStore.CloseSpanning()
                })
            } else {
                // this.$download.zip("/tool/gen/batchGenCode?tables=" + tableNames, "ruoyi");
                download.zip("/tool/gen/batchGenCode?tables=" + data.tableName, data.tableName);
            }

        }

    }

    const onSyncDB = (data: GenTableDomain) => {
        if (data.tableName) {
            synchDb(data.tableName).then((res) => {
                if (res.code === 200) {
                    message.success('同步成功！');
                } else {
                    message.error('同步失败：' + res?.msg);
                }
            }).finally(() => {
                layoutStore.CloseSpanning()
            })
        }

    }
    const onView = (data: GenTableDomain) => {
        // setCodeViewData
        if (data.tableId) {
            layoutStore.OpenSpanning()
            previewTable(data.tableId).then((res) => {
                setCodeViewData(res.data)
                setCodeViewVisible(true)
            }).finally(() => {
                layoutStore.CloseSpanning()
            })
        }

    }

    const onEdit: (data: GenTableDomain) => void = (data) => {
        if (data.tableId) {
            layoutStore.OpenSpanning()
            getGenTable(data.tableId).then((res) => {
                if (res && res.data) {
                    toCard(res.data)
                }
            }).finally(() => {
                layoutStore.CloseSpanning()
            });
        }

    }

    const onImport = (_newdata: GenTableDomain) => {
        setImportModal(true)
    }

    const onDelete = (dedata: GenTableDomain) => {
        if (dedata.tableId) {
            layoutStore.OpenSpanning()
            delTable(dedata.tableId).then(() => {
                setTableListDataSource(tableListDataSource.filter((item) => {
                    return item.tableId !== dedata.tableId
                }))
            }).finally(() => {
                layoutStore.CloseSpanning()
            })
        }
    }


    const headButton = () => {
        return <Space>
            <Button
                size='middle'
                key="add"
                type="primary"
                onClick={() => { onImport(newdata) }}
            >
                导入
            </Button>
        </Space>
    }


    const submit = (genTable: any) => {
        genTable.params = {
            treeCode: genTable.treeCode,
            treeName: genTable.treeName,
            treeParentCode: genTable.treeParentCode,
            parentMenuId: genTable.parentMenuId
        };

        updateGenTable(genTable).then((res) => {
            if (res) {
                if (res.code === 200) {
                    message.success('提交成功！');
                } else {
                    message.error('提交失败：' + res?.msg);
                }
            }

        }).finally(() => {

        });

    }


    const toCard = (data: GenTableDomain) => {
        setQueryValue(queryformRef.current?.getFieldsValue() || {})
        setPageStatus('Card')
        setCardData({ ...data })
    }

    useEffect(() => {
        layoutStore.OpenSpanning();
        getDictDatasByDictTypes('sys_normal_disable').then((res) => {
            const data = res.data;
            if (data['sys_normal_disable']) {
                const d: [] = data['sys_normal_disable'];
                setStatusOptions(d.map((item: DictDataDomain) => {
                    return {
                        label: item.dictLabel,
                        value: item.dictValue
                    }
                }))

            }
        }).finally(() => {
            layoutStore.CloseSpanning()
        })
    }, [])

    useEffect(() => {
        if (pageStatus === 'List') {
            queryformRef.current?.setFieldsValue(queryValue)
        }
    }, [pageStatus])

    //监听分页得操作
    useEffect(() => {
        if (pageInfo.total > 0) {
            //如果原页面有数据，触发查询
            const _data = queryformRef?.current?.getFieldsValue()
            onQuery({...pageInfo,..._data})
        }
    }, [pageInfo.current,, pageInfo.pageSize])


    const onQuery = async (_data: any) => {
        console.log(_data);

        if (_data.createTime) {
            _data.params = {}
            _data.params['beginTime'] = _data.createTime[0];
            _data.params['endTime'] = _data.createTime[1];
            delete _data.createTime
        }

        debugger
        layoutStore.OpenSpanning();
        listTable(_data).then((res) => {
            setTableListDataSource(res.data)
            if (res.total) {
                setPageInfo({ ...pageInfo, total: res.total })
            }

        }).finally(() => {
            layoutStore.CloseSpanning()
        })

        return _data;
    }

    const onPageChange: (current: number, pageSize: number) => void = (current, pageSize) => {
        setPageInfo({ ...pageInfo, current, pageSize });
    };


    return (<PageDiv>{
        pageStatus === 'List' ?
            <PageDiv>
                <QueryFilter<GenTableDomain>
                    defaultCollapsed
                    split
                    span={4}
                    onFinish={(_data) => onQuery({ ...pageInfo, ..._data, current: 1, })}
                    formRef={queryformRef}>

                    <ProFormText key='tableName' name="tableName" label="表名称" />
                    <ProFormText key='tableComment' name="tableComment" label="表描述" />
                    <ProFormDateRangePicker key='createTime' name="createTime" label="创建时间" />
                </QueryFilter>
                <ResizeTable<GenTableDomain>
                    onRow={record => {
                        return {
                            onDoubleClick: event => { onView(record) },
                        };
                    }}
                    dataSource={tableListDataSource}
                    actionRef={actionRef}
                    columns={columns}
                    cardBordered
                    revalidateOnFocus={false}
                    headerTitle={headButton()}
                    pagination={{
                        ...pageInfo,
                        onChange: onPageChange
                    }
                    }
                >
                </ResizeTable>
                <Viewcode datas={codeViewData} visible={codeViewVisible} onCancel={function (): void {
                    setCodeViewVisible(false)
                }} />
                <ImportTable visible={importModal} onOk={() => { setImportModal(false); queryformRef?.current?.submit(); }} onCancel={() => { setImportModal(false) }} />
            </PageDiv > :
            <GenEdit datas={cardData} submit={submit} cancle={function (): void {
                setPageStatus('List')
            }} />}
    </PageDiv>

    )
}
export default Gen;